<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Profile extends MY_Controller {
    private $per_page  = '10';
    private $prev_link  = 'Prev';
    private $next_link  = 'Next';
    private $workerstate = array("overseas","singapore");
    private $profilestatus = array("Initial","Application","Approve","Arrived","Issue","Return","Rejected","Appointment","Cancel");
    
    public function __construct(){
        parent::__construct();
        $this->load->model('profile_model');
        $this->load->model('index_model');
        $this->load->model('user_model');
    }
    
    public function index(){
        if($this->is_logged_in()){
            $config = array();
            $config['per_page']    = $this->per_page;         //每页显示的数据数
            $current_page          = intval($this->input->get_post('per_page',true));  //获取当前分页页码数
            $condition = $this->input->post('condition') == NULL?
                    $this->input->get('condition'):$this->input->post('condition');
            if(0 == $current_page){
               $current_page = 1;
            }
            $offset   = ($current_page - 1 ) * $config['per_page'];          //设置偏移量 限定 数据查询 起始位置（从 $offset 条开始）
            $userid = 0;
            if($this->session->userdata('user')->role == 1){
                $userid = $this->session->userdata('user')->id;
            }
            $ordername = ($this->input->post('ordername') != NULL&&$this->input->post('ordername') != "")
                    ?$this->input->post('ordername'):
                        (($this->input->get('ordername') != NULL&&$this->input->get('ordername') != "")
                            ?$this->input->get('ordername'):"updatetime desc");
            $type = 0;
            if($_GET){
                $type = $this->input->get('type');
            }else if($_POST){
                $type = $this->input->post('type');
            }
            $profile  = $this->profile_model->get_profile($offset,$config['per_page'],$ordername,$userid,$condition,$type);
            $config['base_url']           = base_url('profile/index?').'condition='.$condition."&ordername=".$ordername."&"."&type=".$type."&";
            $config['prev_link']          = $this->prev_link;
            $config['next_link']          = $this->next_link;
            $config['total_rows']         = $profile['total'];         //获取查询数据的总记录数
            $config['use_page_numbers']   = TRUE;            //默认分页URL中是显示每页记录数,启用use_page_numbers后显示的是当前页码
            $config['page_query_string']  = TRUE;            //把 $config['enable_query_strings'] 设置为 TRUE，链接将自动地被用查询字符串（url中的参数）重写。        
            $this->pagination->initialize($config);

            $data = array(
                'profile'  => $profile['res'],
                'total'   => $profile['total'],
                'current_page' => $current_page,
                'per_page'  => $config['per_page'],
                'page'   => $this->pagination->create_links(),
                'condition'  =>  $condition,
                'ordername'=>$ordername,
                'type'=>$type
            );
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('profile/profile_top');
            $this->load->view('profile/index',$data);
            $this->load->view('profile/profile_bottom');
            $this->load->view('templates/footer');
        }else{
            redirect('user/login');
        }
    }
    
    public function order(){
        if($this->is_logged_in()){
            $config = array();
            $config['per_page']    = $this->per_page;         //每页显示的数据数
            $current_page          = intval($this->input->get_post('per_page',true));  //获取当前分页页码数
            $condition = $this->input->post('condition') == NULL?
                    $this->input->get('condition'):$this->input->post('condition');
            if(0 == $current_page){
               $current_page = 1;
            }
            $type = 0;
            if($_GET){
                $type = $this->input->get('type');
            }else if($_POST){
                $type = $this->input->post('type');
            }
            $ordername = ($this->input->post('ordername') != NULL&&$this->input->post('ordername') != "")
                    ?$this->input->post('ordername'):
                        (($this->input->get('ordername') != NULL&&$this->input->get('ordername') != "")
                            ?$this->input->get('ordername'):"o.updatetime desc");
            $offset   = ($current_page - 1 ) * $config['per_page'];          //设置偏移量 限定 数据查询 起始位置（从 $offset 条开始）       
            $order  = $this->profile_model->get_order($offset,$config['per_page'],$ordername,$condition,$type);
            $config['base_url']           = base_url('profile/order?').'condition='.$condition."&ordername=".$ordername."&"."&type=".$type."&";
            $config['prev_link']          = $this->prev_link;
            $config['next_link']          = $this->next_link;
            $config['total_rows']         = $order['total'];         //获取查询数据的总记录数
            $config['use_page_numbers']   = TRUE;            //默认分页URL中是显示每页记录数,启用use_page_numbers后显示的是当前页码
            $config['page_query_string']  = TRUE;            //把 $config['enable_query_strings'] 设置为 TRUE，链接将自动地被用查询字符串（url中的参数）重写。        
            $this->pagination->initialize($config);
            
            foreach ($order['res'] as $key => $value) {
                $workers = $this->index_model->getWorkersByOrderID($value['id']);
                $order['res'][$key]['workernum'] = count($workers);
            }

            $data = array(
                'order'  => $order['res'],
                'total'   => $order['total'],
                'current_page' => $current_page,
                'per_page'  => $config['per_page'],
                'page'   => $this->pagination->create_links(),
                'condition'  =>  $condition,
                'ordername'=>$ordername,
                'type'=>$type
            );
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('index/index_top');
            $this->load->view('profile/order',$data);
            $this->load->view('index/index_bottom');
            $this->load->view('templates/footer');
        }else{
            redirect('user/login');
        }
    }
    
    public function new_order(){
        if($this->is_logged_in()){
            if(!$_POST){
                $data['company'] = $this->index_model->getcompanybytype(1);
                $data['orders'] = $this->profile_model->getAllsn();
                $data['marketing'] = $this->user_model->getAllEmployeeUser();
                $this->load->view('templates/header');
                $this->load->view('templates/left');
                $this->load->view('index/index_top');
                $this->load->view('profile/neworder',$data);
                $this->load->view('index/index_bottom');
                $this->load->view('templates/footer');
            }else{
                $id = $this->profile_model->neworder();
                redirect("profile/order");
            }
        }else{
            redirect('user/login');
        }
    }
    
    public function deleteorder(){
        if($this->is_logged_in()){
            $id = $this->input->get("id");
            $this->profile_model->deleteorder();
            $this->index_model->setNULLByOrderID($id);
            redirect("profile/order");
        }else{
            redirect('user/login');
        }
    }
    
    public function order_detail($id){
        if($this->is_logged_in()){
            if(!$_POST){
                $data['company'] = $this->index_model->getcompanybytype(1);
                $data['orders'] = $this->profile_model->getAllsn();
                $data['order'] = $this->profile_model->getOrderByid($id);
                $workers = $this->index_model->getWorkersByOrderID($data['order']['id']);
                $data['order']['workerids'] = '';
                $data['order']['workers'] = '';
                foreach ($workers as $key => $worker) {
                    $data['order']['workerids'] .= "_".$worker['id'];
                    $data['order']['workers'] .= "-".$worker['name'];
                }
                $data['marketing'] = $this->user_model->getAllEmployeeUser();
                $this->load->view('templates/header');
                $this->load->view('templates/left');
                $this->load->view('index/index_top');
                $this->load->view('profile/updateorder',$data);
                $this->load->view('index/index_bottom');
                $this->load->view('templates/footer');
            }else{
                $this->profile_model->updateorder();
                redirect("profile/order");
            }
        }else{
            redirect('user/login');
        }
    }
    
    public function choice_workers($str=""){
        $condition = $this->input->post('condition') == NULL?
                $this->input->get('condition'):$this->input->post('condition');
        if($str == "radio"){
            $candidate  = $this->index_model->getAllworkers($condition);
        }else{
            $candidate  = $this->index_model->getemptyworkers($condition);
        }
        
        foreach ($candidate['res'] as $key => $value) {
            $birthday = $value['birthday'];
            $age = date('Y', time()) - date('Y', strtotime($birthday)) - 1;  
            if (date('m', time()) == date('m', strtotime($birthday))){
                if (date('d', time()) > date('d', strtotime($birthday))){  
                    $age++;  
                }  
            }elseif (date('m', time()) > date('m', strtotime($birthday))){  
                $age++;  
            }  
            $candidate['res'][$key]['age'] = $age;
            $candidate['res'][$key]['locationstr'] = $this->workerstate[$value['location']>1?1:$value['location']];
        }

        $data = array(
            'title' => "Choice Candidate",
            'str' => $str,
            'candidates'  => $candidate['res'],
            'condition'  =>  $condition,
        );
        $this->load->view('choice/choice_workers',$data);
    }
    
    public function choice_orders(){
        $condition = $this->input->post('condition') == NULL?
            $this->input->get('condition'):$this->input->post('condition');
        //查询出所有未申请的订单
        $orders = $this->profile_model->getOrderByType(0,$condition);
        //添加该订单下的工人到没个订单
        foreach ($orders as $index => $order) {
            $worker = $this->index_model->getWorkersByOrderID($order['id']);
            $orders[$index]['workerid'] = '';
            $orders[$index]['worker'] = '';
            if(count($worker)!=0){
                $orders[$index]['workerid'] .= $worker['id'];
                $orders[$index]['worker'] .= $worker['name'];
            }
        }
        $data = array(
            'title' => "Choice Orders",
            'orders'  => $orders,
            'condition'  =>  $condition,
        );
        $this->load->view('choice/choice_orders',$data);    
    }
    
    public function choice_company(){
        $condition = $this->input->post('condition') == NULL?
            $this->input->get('condition'):$this->input->post('condition');
        $conpany = $this->index_model->getcompanybytype(1,$condition);
        $data = array(
            'title' => "Choice Company",
            'orders'  => $conpany,
            'condition'  =>  $condition,
        );
        $this->load->view('choice/choice_company',$data);   
    }
    
    public function choice_profile(){
        $condition = $this->input->post('condition') == NULL?
            $this->input->get('condition'):$this->input->post('condition');
        $profile = $this->profile_model->getProfileByCondition($condition);
        $data = array(
            'title' => "Choice Profile",
            'profile'  => $profile,
            'condition'  =>  $condition,
        );
        $this->load->view('choice/choice_profile',$data);   
    }
    
    public function setNULLByOrderID($id){
        $this->index_model->setNULLByOrderID($id);
        redirect("profile/order_detail/".$id);
    }
    
    /**
     * 查看上传待遇确认书洁面
     * @param type $id 订单id
     */
    public function submit_confirmation_letter($id){
        $condition = $this->input->post('condition') == NULL?
                $this->input->get('condition'):$this->input->post('condition');
        $data['search'] = array('ordersn' => $id);
        $data['condition'] = $condition;
        $candidate  = $this->index_model->getworkers($data);
        foreach ($candidate as $key => $value) {
            $confirmationletter = $this->index_model->getconfirmationletterbyworkerid($value['id']);
            if(count($confirmationletter) == 0){
                $confirmationletter['id'] = "0";
                $confirmationletter['path'] = "Do not upload.";
            }
            $candidate[$key]['confirmationletter'] = $confirmationletter;
        }

        $data = array(
            'orderid'=>$id,
            'title' => "Submit Confirmation Letter",
            'candidates'  => $candidate,
            'condition'  =>  $condition,
        );
        $this->load->view('choice/submit_confirmation_letter',$data);
    }
    
    /**
     * 新增或修改工人的待遇确认书
     * @param type $workerid
     */
    public function edit_confirmationletter($workerid){
        $orderid = $this->input->post("orderid");
        if(!$_POST){
        }else{
            $id = $this->input->post("id");
            $config['upload_path'] = './resource/uploadfile/';
            $config['allowed_types']    = 'gif|jpg|png|jpeg|docx|doc';
            $config['file_name'] = 'comfirmation_letter_'.time();
            $this->load->library('upload', $config);
            if ($this->upload->do_upload('path')){
                $udata = $this->upload->data();
                $resumefile = $udata['file_name'];
                $id = $this->input->post("id");
                $this->index_model->editconfirmationletter($resumefile,$workerid,$id);
            }else{
                $udata = $this->upload->data();
                var_dump($udata);
                echo $this->upload->display_errors();
            }
        }
        redirect("profile/submit_confirmation_letter/".$orderid);
    }
    
    public function updatesource(){
        $data['source'] = $this->input->post("source");
        $this->index_model->update("profile",$data,$this->input->post("id"));
    }
    
    public function detail_profile($profileid){
        if($this->is_logged_in()){
            //根据得到profile信息
            $profile = $this->profile_model->getProfileByID($profileid);
            $houseagent = $this->index_model->getcompanybytype(3);
            //是否存在订单
            if($profile['application'] == 2 || $profile['application'] == 4){//不存在订单
                $order = array(
                    'id'=>0,
                    'position'=>'',
                    'gender'=>0,
                    'salary'=>'',
                    'worktype'=>0,
                    'starttime'=>NULL,
                    'endtime'=>NULL,
                    'workintro'=>'',
                    'comment'=>''
                );
                //查询出申请单下的所有工人
                $worker = $this->index_model->getByID('workers',$profile['workerid']);
                //查询出该申请公司名称
                $company = $this->index_model->getcompanybyid($profile['companyid']);
            }else{//存在订单
                //得到profile名称
                $profilename = $profile['name'];
                $profilenames = explode("_", $profilename);

                //得到订单id
                $orderid = $profile['ordersn'];
                //根据订单id查询出订单
                $order = $this->index_model->getByID('order',$orderid);

                //查询出工人
                $workerid = $profile['workerid'];
                $worker = $this->index_model->getByID('workers',$workerid);
                //查询出该订单公司名称
                $company = $this->index_model->getcompanybyid($order['companyid']);
            }
            //得到公司行业
            $industry = $this->index_model->getByID("industry",$company['industry']);
            if(count($industry) == 0){
                $industry['name'] = "";
            }
            //得到业务员账号id
            $userid = $profile['employeeid'];
            //根据userid得到员工信息
            $employee = $this->user_model->getEmployeeByUserID($userid);
            //得到attachments的关联类型
            $attachmenttype = 1;
            if($profile['application'] == 3){
                $rnum = explode("_",$profile['name']);
                $rnum = str_replace("R", "", $rnum[0]);

                if(is_numeric($rnum)){
                    $attachmenttype = $rnum;
                }
            }
            //根据profileid得到该申请的文档
            $attachments = $this->index_model->getAttachmentsBYAssociatedID($profile['id'],$attachmenttype);
            //根据工人id得到工人文档
            $attachments0 = $this->index_model->getAttachmentsBYAssociatedID($worker['id'],0);
            if(count($attachments) == 0){
                $attachments = $attachments0;
            }else if(count($attachments0) == 0){
            }else{
                $attachments = array_merge($attachments0,$attachments);
            }
            //构建数据数组
            $data = array(
                'profile'=>$profile,
                'order'=>$order,
                'worker'=>$worker,
                'company'=>$company,
                'employee'=>$employee,
                'industry'=>$industry,
                'attachments'=>$attachments,
                'houseagent'=>$houseagent,
                'attachmenttype'=>$attachmenttype
            );
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('profile/profile_top');
            $this->load->view('profile/profiledetail',$data);
            $this->load->view('profile/profile_bottom');
            $this->load->view('templates/footer');
        }else{
            redirect('user/login');
        }
    }
    
    /**
     * 上传或修改政府批准准证
     * @param type $id 申请id
     */
    public function edit_approvingletter($id){
        $config['upload_path'] = './resource/uploadfile/';
        $config['allowed_types']    = 'gif|jpg|png|jpeg|doc|docx';
        $config['file_name'] = 'approving_letter_'.time();
        $this->load->library('upload', $config);
        if ($this->upload->do_upload('path')){
            $udata = $this->upload->data();
            //准证名称
            $resumefile = $udata['file_name'];
            //根据profileid查询出profile
            $profile = $this->index_model->getByID("profile",$id);
            $profilename = str_replace("Pending","Approve",$profile['name']);;
            //构造profile数据
            $data = array(
                "name"           =>$profilename,
                "approvingletter"=>$resumefile,
                "type"           =>1,
                "updatetime"     =>time()
            );
            //跟新profile
            $this->index_model->update("profile",$data,$id);
            //根据orderid跟新order
            $orderid = $profile['ordersn'];
            $data = array(
                "type"           =>2,
                "updatetime"     =>time()
            );
            $this->index_model->update("order",$data,$orderid);
            //查询出订单下的所有工人
            $workers = $this->index_model->getWorkersByOrderID($orderid);
            $data = array(
                "state"           =>3
            );
            foreach ($workers as $key => $value) {
                $this->index_model->update("workers",$data,$value['id']);
            }
        }
        redirect("profile/detail_profile/".$id);
    }
    
    //进入租房详细界面
    public function tenement($workerid){
        if($_POST){
            $data = array(
                "housecompanyid"=>$this->input->post("houseconpanyid"),
                "address"=>$this->input->post("address"),
                "rent"=>$this->input->post("rent"),
            );
            $this->index_model->update("workers",$data,$workerid);
        }
        //查询出工人详细信息
        $worker = $this->index_model->getByID("workers",$workerid);
        //租房中介id
        $housecompanyid = $worker['housecompanyid'];
        if($housecompanyid > 0){
            //查询出员工的房东公司信息
            $houseagent = $this->index_model->getcompanybyid($housecompanyid);
        }else{
            $houseagent = array(
                'name' =>'',
                'address' =>'',
                'person' =>'',
                'email' =>'',
                'number' =>'',
                'comment' =>'',
            );
        }
        //查询出所有房东中介
        $houseagents = $this->index_model->getcompanybytype(3);
        $data = array(
            'title'         =>$worker['name'],
            'worker'        =>$worker,
            'houseconpanyid'=>$housecompanyid,
            'houseagent'    =>$houseagent,
            'houseagents'   =>$houseagents
        );
        $this->load->view('choice/tenement',$data);
    }
    /**
     * 删除项目
     * @param type $profileid 项目id
     */
    public function delete($profileid){
        //查询出profile
        $profile = $this->index_model->getByID("profile",$profileid);
        //判断项目是否有订单
        $workerid = $profile['workerid'];//工人id
        $orderid = $profile['ordersn'];//订单id
        //清楚工人对的ordersn
        $data = array(
            'ordersn'=>NULL,
            'associatedtype'=>0,
            'state'=>0
        );
        $this->index_model->update("workers",$data,$workerid);
        if($orderid != "" && $orderid*1 > 0){
            $data = array(
                'type'=>0
            );
            $this->index_model->update("order",$data,$orderid);
        }
        $this->profile_model->My_Delete("profile",$profileid);
        redirect("profile/index");
    }
    
    /**
     * 选择订单，生成profile
     */
    public function select_order(){
        $condition = $this->input->post("condition");
        //查询出为申请或作废的订单
        $orders = $this->profile_model->getUseableOrder($condition);
        $data = array("orders"=>$orders,"title"=>"New Profile","condition"=>$condition);
        $this->load->view('choice/orders',$data);
    }
    
    public function new_profile(){
        if(!$_POST){
            //查询出所有国内代理
            $data['agent'] = $this->index_model->getcompanybytype(2);
            $data['marketing'] = $this->user_model->getAllEmployeeUser();
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('profile/profile_top');
            $this->load->view('profile/newprofile',$data);
            $this->load->view('profile/profile_bottom');
            $this->load->view('templates/footer');
        }else{
            $existorder = $this->input->post("existorder");
            if($existorder*1 == 1){//根据订单生成profile
                //跟新order
                $orderid = $this->input->post("orderid");
                $saleserid = $this->input->post('saleser');
                $data = array(
                    'type' => 1,
                    'saleser'=>$saleserid,
                    'companyid' => $this->input->post("companyid"),
                    'updatetime' => time()
                );
                $this->index_model->update('order',$data,$orderid);
                
                //跟新worker
                $workerid = $this->input->post('workersid');
                $agentid = $this->input->post("agent");
                $data = array('state'=>1);
                if($agentid != NULL && $agentid*1 > 0){
                    $data['companyid'] = $agentid;
                }
                $this->index_model->update("workers",$data,$workerid);
                
                //新增profile
                //查询出订单信息
                $order = $this->index_model->getByID("order",$orderid);
                //查询出订单下的工人
                $worker = $this->index_model->getByID("workers",$workerid);
                //根据工人，查询出工人的中介公司信息
                $intermediary = $this->index_model->getByID("company",$worker['companyid']);
                //查询出该订单公司名称
                $company = $this->index_model->getByID("company",$order['companyid']);
                //在本地缓存总取出userid
                $userid = $this->session->userdata('user')->id;
                //得到销售id
                $saleserid = $this->input->post('saleser');
                //根据saleserid得到员工信息
                $user = $this->index_model->getByID("user",$saleserid);
                //构建申请表数据
                $data = array(
                    'name'      => $order['sn'].'_'.$company['name'].'_'.$worker['name'].'_'.$order['position'].'_'.$user['username'].'_'.$intermediary['name'].'_Initial',
                    'ordersn'   => $order['id'],
                    'source' => $this->input->post('source'),
                    'workerid'=>$worker['id'],
                    'employeeid'=> $userid,
                    'saleser'=>$saleserid,
                    'createtime'=> time(),
                    'updatetime'=> time(),
                    'status'=>0,
                    'application'=>$this->input->post("existorder")
                );
                //新增申请表
                $this->profile_model->create("profile",$data);
            }else if($existorder*1 == 3){
                $orderid = $this->input->post("orderid");
                $saleserid = $this->input->post('saleser');
                $data = array(
                    'type' => 1,
                    'saleser'=>$saleserid,
                    'companyid' => $this->input->post("companyid"),
                    'updatetime' => time()
                );
                //跟新order
                $this->index_model->update('order',$data,$orderid);
                
                $profileid = $this->input->post('profileid');
                $profile = $this->profile_model->getProfileByID($profileid);
                
                $worker = $this->index_model->getByID('workers',$profile['workerid']);
                
                $data = array('state'=>1);
                $agentid = $this->input->post("agent");
                if($agentid != NULL && $agentid*1 > 0){
                    $data['companyid'] = $agentid;
                }
                $this->index_model->update("workers",$data,$worker['id']);
                
                //查询出订单信息
                $order = $this->index_model->getByID("order",$orderid);
                //根据工人，查询出工人的中介公司信息
                $intermediary = $this->index_model->getByID("company",$worker['companyid']);
                //查询出该订单公司名称
                $company = $this->index_model->getByID("company",$order['companyid']);
                //在本地缓存总取出userid
                $userid = $this->session->userdata('user')->id;
                //得到销售id
                $saleserid = $this->input->post('saleser');
                //根据saleserid得到员工信息
                $user = $this->index_model->getByID("user",$saleserid);
                
                //查询当前工人关联了多少个profile
                $profiles = $this->index_model->getAllByData(array('workerid'=>$worker['id']),"profile");
                //新增profile
                $data = array(
                    'name'      => 'R'.(count($profiles)).'_'.$order['sn'].'_'.$company['name'].'_'.$worker['name'].'_'.$order['position'].'_'.$user['username'].'_'.$intermediary['name'].'_Initial',
                    'ordersn'   => $order['id'],
                    'source' => $this->input->post('source'),
                    'workerid'=>$worker['id'],
                    'employeeid'=> $userid,
                    'saleser'=>$saleserid,
                    'createtime'=> time(),
                    'updatetime'=> time(),
                    'status'=>0,
                    'application'=>$this->input->post("existorder")
                );
                //新增申请表
                $this->profile_model->create("profile",$data);
            }else if($existorder*1 == 2 || $existorder*1 == 4){//直接生成profile
                $workerid = $this->input->post('workersid');
                $agentid = $this->input->post("agent");
                if($agentid != NULL && $agentid*1 > 0){
                    $data['companyid'] = $agentid;
                    $this->index_model->update("workers",$data,$workerid);
                }
                $companyname = $this->input->post('name');
                //查询出工人信息
                $worker = $this->index_model->getByID('workers',$workerid);
                //根据第一个工人，查询出第一个工人的中介公司信息
                $intermediary = $this->index_model->getByID("company",$worker['companyid']);
                //在本地缓存总取出userid
                $userid = $this->session->userdata('user')->id;
                //得到销售id
                $saleserid = $this->input->post('saleser');
                //根据userid得到员工信息
                $user = $this->index_model->getByID("user",$saleserid);
                //构建申请表数据
                $data = array(
                    'name'      => '代_'.$companyname.'_'.$worker['name'].'_'.$worker['position'].'_'.$user['username'].'_'.$intermediary['name'].'_Initial',
                    'source' => $this->input->post('source'),
                    'companyid' => $this->input->post("companyid"),
                    'workerid'=>$worker['id'],
                    'saleser' => $saleserid,
                    'employeeid'=> $userid,
                    'createtime'=> time(),
                    'updatetime'=> time(),
                    'status'=>0,
                    'application'=>$existorder
                );
                //新增申请表
                $profileid = $this->profile_model->create("profile",$data);
                $data = array(
                    'state'=>1
                );
                $this->index_model->update("workers",$data,$workerid);
            }
            redirect("profile/index");
        }
    }
    
    /**
     * 修改profile状态
     * @param type $profileid
     */
    public function edit_profile($profileid){
//        $profile = $this->index_model->getByID("profile",$profileid);
        $profilename = $this->input->post("profilename");
        $status = $this->input->post("status");
        $statusname = $this->profilestatus[$status];
        $profilenamearr = explode("_", $profilename);
        $currentstatusname = $profilenamearr[count($profilenamearr)-1];
        $profilename = str_replace($currentstatusname,$statusname,$profilename);
        $buysbdate = strtotime($this->input->post("buysbdate"));
        $flightno = $this->input->post("flightno");
        $terminal = $this->input->post("terminal");
        
        $data = array(
            'name'      => $profilename,
            'updatetime'=> time(),
            'status'=>$status,
            'buysbdate'=>$buysbdate,
            'flightno'=>$flightno,
            'terminal'=>$terminal
        );
        $statustime = $this->input->post("statustime");
        $times1 = explode(" ", $statustime);
        $time1 = $times1[1];
        if($statustime != NULL && trim($statustime) != ''){
            $noticetime = strtotime($times1[0]);
            $statustime = strtotime($statustime);
            if($data['status']*1 == 1){
                $data['applytime'] = $statustime;
            }else if($data['status']*1 == 2){
                $data['approvetime'] = $statustime;
                //添加提醒
                $workerid = $this->input->post("workerid");
                $workername = $this->input->post("workername");
                $worktype = $this->input->post("worktype");
                $application = $this->input->post("application");
                $notice1 = array(
                    'title'=>'Need issue '.$workername,
                    'noticedate'=>$noticetime*1+60*60*24*2,
                    'noticetime'=>$time1,
                    'type'=>3,
                    'association'=>$workerid,
                    'employeeid'=> $this->session->userdata('user')->id,
                    'updatetime'=> time(),
                );
                if($worktype*1 == 1 || $application*1 == 3){
                    $notice1['noticedate'] = $noticetime*1+60*60*24*7;
                }
                //查询当前员工是否有issue提醒
                $notice = $this->index_model->getOneByData(array('association'=>$workerid,"type"=>3),"notice");
                if(count($notice)==0){//新增issue提醒
                    $notice1['createtime'] = time();
                    $notice1['updatetime'] = $notice1['createtime'];
                    $this->profile_model->create("notice",$notice1);
                }else if($notice['id']*1 > 0){//跟新提醒
                    $this->index_model->update("notice",$notice1,$notice['id']);
                }
                //查询当前员工是否有pass port提醒
                $passportnotice = $this->index_model->getOneByData(array('association'=>$workerid,"type"=>4),"notice");
                $notice1['title'] = $workername.' need Make Work Pass';
                $notice1['noticedate'] = $noticetime*1+60*60*24*9;
                $notice1['type'] = 4;
                if($worktype*1 == 1 || $application*1 == 3){
                    $notice1['noticedate'] = $noticetime*1+60*60*24*14;
                }
                if(count($passportnotice)==0){//新增passport提醒
                    $notice1['createtime'] = time();
                    $notice1['updatetime'] = $notice1['createtime'];
                    $this->profile_model->create("notice",$notice1);
                }else if($passportnotice['id']*1 > 0){//跟新passport提醒
                    $this->index_model->update("notice",$notice1,$passportnotice['id']);
                }
            }else if($data['status']*1 == 3){
                $data['arrivedtime'] = $statustime;
                //添加提醒
                $workerid = $this->input->post("workerid");
                $workername = $this->input->post("workername");
                $worktype = $this->input->post("worktype");
                $application = $this->input->post("application");
                $notice1 = array(
                    'title'=>$workername." need pick-up",
                    'noticedate'=>$noticetime,
                    'noticetime'=>$time1,
                    'type'=>1,
                    'association'=>$workerid,
                    'employeeid'=> $this->session->userdata('user')->id,
                    'updatetime'=> time(),
                );
                //查询当前员工是否有接机提醒
                $notice = $this->index_model->getOneByData(array('association'=>$workerid,"type"=>1),"notice");
                $noticeid = 0;
                if(count($notice)==0){//新增提醒
                    $notice1['createtime'] = $notice1['updatetime'];
                    $noticeid = $this->profile_model->create("notice",$notice1);
                }else if($notice['id']*1 > 0){//跟新提醒
                    $this->index_model->update("notice",$notice1,$notice['id']);
                    $noticeid = $notice['id'];
                }
                $pickup = $this->index_model->getOneByData(array('noticeid'=>$notice['id']),"pickup");
                $notice2 = array(
                    'fltno'=>$this->input->post("flightno"),
                    'terminal'=>$this->input->post("terminal"),
                    'arrivetime'=>$statustime,
                    'noticeid'=>$noticeid
                );
                if(count($pickup)==0){//新增接机
                    $this->profile_model->create("pickup",$notice2);
                }else if($pickup['id']*1 > 0){//跟新接机
                    $this->index_model->update("pickup",$notice2,$pickup['id']);
                }
            }else if($data['status']*1 == 4){
                $data['issuetime'] = $statustime;
                $data['wi'] = $this->input->post("wi");
                $data['wici'] = $this->input->post("wici");
            }else if($data['status']*1 == 5){
                $data['returntime'] = $statustime;
                $workerid = $this->input->post("workerid");
                $workername = $this->input->post("workername");
                $notice1 = array(
                    'title'=>$workername.' Return',
                    'noticedate'=>$noticetime,
                    'noticetime'=>$time1,
                    'type'=>5,
                    'association'=>$workerid,
                    'employeeid'=> $this->session->userdata('user')->id,
                    'updatetime'=> time(),
                    'createtime'=> time()
                );
                $this->profile_model->create("notice",$notice1);
            }else if($data['status']*1 == 6){
                $data['rejectedtime'] = $statustime;
            }else if($data['status']*1 == 7){
                $data['othertime'] = $statustime;
            }else if($data['status']*1 == 8){
                $data['canceldate'] = $statustime;
                $lastdatestr = $this->input->post("lastdate");
                if($lastdatestr != NULL){
                    $times2 = explode(" ", $lastdatestr);
                    $time2 = $times2[1];
                }
                $lastdate = strtotime($times2[0]);
                $data['lastdate'] = strtotime($lastdatestr);
                //添加提醒
                if($lastdatestr != NULL){
                    $workerid = $this->input->post("workerid");
                    $workername = $this->input->post("workername");
                    $notice1 = array(
                        'title'=>$workername.' left 3 days in sgp',
                        'noticedate'=>$lastdate*1-60*60*24*3,
                        'noticetime'=>$time2,
                        'type'=>5,
                        'association'=>$workerid,
                        'employeeid'=> $this->session->userdata('user')->id,
                        'updatetime'=> time(),
                    );
                    $notice = $this->index_model->getOneByData(array('association'=>$workerid,"type"=>5),"notice");
                    if(count($notice)==0){//新增提醒
                        $notice1['createtime'] = $notice1['updatetime'];
                        $noticeid = $this->profile_model->create("notice",$notice1);
                    }else if($notice['id']*1 > 0){//跟新提醒
                        $this->index_model->update("notice",$notice1,$notice['id']);
                    }
                }
            }
        }
        if($data['status'] == 0 || $data['status'] == 1){
            $data['type'] = 0;
        }else if($data['status'] == 3 || $data['status'] == 2 || $data['status'] == 4){
            $data['type'] = 1;
        }else{
            $data['type'] = 2;
        }
        if($this->input->post("mitime") != ""){
            $data['mitime'] = $this->input->post("mitime");
        }
        if($this->input->post("wicitime") != ""){
            $data['wicitime'] = $this->input->post("wicitime");
        }
        $this->index_model->update("profile",$data,$profileid);
        
        $accomodation = $this->input->post("accomodation");
        $data = array(
            "number"=>$this->input->post("workernumber"),
            'updatetime'=> time(),
        );
        if($accomodation*1 == 1){
            $data['isneedaccommodation'] = 1;
            $housecompany = $this->input->post("housecompanyid");
            $housecompanyarr = explode(":", $housecompany);
            if(count($housecompanyarr) == 3 && $housecompanyarr[0]*1>0){
                $data['housecompanyid'] = $housecompanyarr[0];
            }
            $data['address'] = $housecompany;
        }
        $this->index_model->update("workers",$data,$this->input->post("workerid"));
        
        redirect("profile/detail_profile/".$profileid);
    }
    
    /**
     * 归档profile
     */
    public function archived(){
        $id = $this->input->get("id");
        $type = $this->input->get("type");
        if($type*1 == 0){//profile归档
            $this->index_model->update("profile",array('type'=>4,'updatetime'=>time()),$id);
            //查询出profile
            $profile = $this->index_model->getByID("profile",$id);
            $workerid = $profile['workerid'];//工人id
            $orderid = $profile['ordersn'];//订单id
            //工人归档
            $this->index_model->update("workers",array('state'=>4,'updatetime'=>time()),$workerid);
            //订单归档
            if($orderid!=NULL&&$orderid*1>0){
                //订单归档
                $this->index_model->update("order",array('type'=>4,'updatetime'=>time()),$orderid);
            }
            redirect("profile/index");
        }else if($type*1 == 1){
            //工人归档
            $this->index_model->update("workers",array('state'=>4,'updatetime'=>time()),$id);
            redirect("index/index");
        }else if($type*1 == 2){
            //订单归档
            $this->index_model->update("order",array('type'=>4,'updatetime'=>time()),$id);
            redirect("profile/order");
        }else if($type*1 == 3){//将profile放入垃圾箱
            $this->index_model->update("profile",array('type'=>5,'updatetime'=>time()),$id);
            //查询出profile
            $profile = $this->index_model->getByID("profile",$id);
            $workerid = $profile['workerid'];//工人id
            $orderid = $profile['ordersn'];//订单id
            //工人归档
            $this->index_model->update("workers",array('state'=>4,'updatetime'=>time()),$workerid);
            //订单归档
            if($orderid!=NULL&&$orderid*1>0){
                //订单归档
                $this->index_model->update("order",array('type'=>4,'updatetime'=>time()),$orderid);
            }
            redirect("profile/index");
        }
    }
    
    /**
     * 恢复归档的profile
     */
    public function restore(){
        $id = $this->input->get("id");
        $type = $this->input->get("type");
        if($type*1 == 0){
            $this->index_model->update("profile",array('type'=>1,'updatetime'=>time()),$id);
            //查询出profile
            $profile = $this->index_model->getByID("profile",$id);
            $workerid = $profile['workerid'];//工人id
            $orderid = $profile['ordersn'];//订单id
            //工人归档
            $this->index_model->update("workers",array('state'=>1,'updatetime'=>time()),$workerid);
            if($orderid!=NULL&&$orderid*1>0){
                //订单归档
                $this->index_model->update("order",array('type'=>1,'updatetime'=>time()),$orderid);
            }
            redirect("profile/index");
        }else if($type*1 == 1){
            //工人归档
            $this->index_model->update("workers",array('state'=>0,'updatetime'=>time()),$id);
            redirect("index/index");
        }else if($type*1 == 2){
            //订单归档
            $this->index_model->update("order",array('type'=>0,'updatetime'=>time()),$id);
            redirect("profile/order");
        }
    }
    
    public function profile_edit(){
        if($_GET){
            $id = $this->input->get("id");
            //查询出profile
            $profile = $this->index_model->getByID("profile",$id);
            //查询出工人
            $workerid = $profile['workerid'];
            $worker = $this->index_model->getByID("workers",$workerid);
            //是否存在订单
            if(($profile['application'] == 1 || $profile['application'] == 3)&&$profile['ordersn'] != NULL && $profile['ordersn']*1>0){
                //得到订单
                $orderid = $profile['ordersn'];
                $order = $this->index_model->getByID("order",$orderid);
                //根据订单得到公司
                $companyid = $order['companyid'];
                $company = $this->index_model->getByID("company",$companyid);
            }else{
                //构造空的order对象
                $order = array("id"=>0,'sn'=>'');
                //根据profile得到公司
                $companyid = $profile['companyid'];
                $company = $this->index_model->getByID("company",$companyid);
            }
            $agent = $this->index_model->getcompanybytype(2);
            $marketing = $this->user_model->getAllEmployeeUser();
            
            $data = array(
                'profile'=>$profile,
                'worker'=>$worker,
                'order'=>$order,
                'company'=>$company,
                'agent'=>$agent,
                'marketing'=>$marketing,
            );
            $this->load->view('templates/header');
            $this->load->view('templates/left');
            $this->load->view('profile/profile_top');
            $this->load->view('profile/profile_edit',$data);
            $this->load->view('profile/profile_bottom');
            $this->load->view('templates/footer');
        }else if($_POST){
            $id = $this->input->post("id");
            $lastapplication = $this->input->post("lastapplication");
            $application = $this->input->post('application');
            $orderid = $this->input->post("orderid");
            $companyid = $this->input->post("companyid");
            $workerid = $this->input->post("workersid");
            $agentid = $this->input->post('agent');
            $saleserid = $this->input->post('saleser');
            $source = $this->input->post("source");
            
            $profile = $this->index_model->getByID("profile",$id);
            //重置原worker信息
            $this->index_model->update('workers',array('state'=>0,'updatetime'=>time()),$profile['workerid']);
            
            //跟新worker
            $data = array('state' => 1,'updatetime' => time());
            if($agentid != NULL && $agentid*1 > 0){
                $data['companyid'] = $agentid;
            }
            $this->index_model->update('workers',$data,$workerid);
            
            if($application == 1 || $application == 3){
                if($lastapplication != 2 && $lastapplication != 4){
                    //重置原order信息
                    $this->index_model->update('order',array('type'=>0,'updatetime'=>time()),$profile['ordersn']);
                }
                
                //跟新order
                $data = array('type' => 1,'saleser'=>$saleserid,'companyid' => $companyid,'updatetime' => time());
                $this->index_model->update('order',$data,$orderid);
            }else{
                if($lastapplication == 1 || $lastapplication == 3){
                    //重置原order信息
                    $this->index_model->update('order',array('type'=>0,'updatetime'=>time()),$profile['ordersn']);
                }
            }
            
            //跟新profile
            $data = array(
                'source'=>$source,
                'saleser'=>$saleserid,
                'updatetime'=> time(),
                'application'=>$application
            );
            
            if($application != 3){
                $data['workerid'] = $workerid;
            }
            
            if($application == 1 || $application == 3){
                $data['companyid'] = NULL;
                $data['ordersn'] = $orderid;
            }else{
                $data['companyid'] = $companyid;
                $data['ordersn'] = NULL;
            }
            
            $names = explode("_", $profile['name']);
            $name = '';
            if($lastapplication*1 == 3 && $application*1 == 3){
                $name .= $names[0];
            }
            
            if($application == 1 || $application == 3){//存在订单
                $order = $this->index_model->getByID("order",$orderid);
                if($name == ""){
                    $name = $order['sn'];
                }else{
                    $name .= "_".$order['sn'];
                }
            }else{
                $name = "代";
            }
            $company = $this->index_model->getByID("company",$companyid);
            $name .= "_".$company['name'];
            $worker = $this->index_model->getByID("workers",$workerid);
            $name .= "_".$worker['name'];
            if($application == 1 || $application == 3){//存在订单
                $name .= "_".$order['position'];
            }else{
                $name .= "_".$worker['position'];
            }
            $salesman = $this->index_model->getByID("user",$saleserid);
            $name .= "_".$salesman['username'];
            $intermediary = $this->index_model->getByID("company",$agentid);
            $name .= "_".$intermediary['name'];
            $name .= "_".$this->profilestatus[$profile['status']];
            $data['name'] = $name;
            $this->index_model->update('profile',$data,$id);
            redirect("profile/profile_edit?id=".$id);
        }
    }
}